<?php
/**
 * 文章管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Common\Model\EditorModel;
use Common\Model\ArticleModel;
use Common\Model\UtilsModel;
use Think\Page;
class ArticleController extends BaseController{

	/**
	 * 文章列表页
	 * Author: shijy
	 */
	public function index(){
		$export		=I('get.export',0,'int');
		$audit		=I('get.audit',0,'int');
		$where='1';

		if(ARTICLE_CLIENT_SHOW){	//展现渠道
			$clientShow=I('get.clientShow',0,'int');
			if($clientShow>0){
				$where .=" and find_in_set({$clientShow},clientShow)";
			}
			$this->smarty->assign('clientShow',C('CLIENT_SHOW'));
			$this->smarty->assign('selectedClientShow',$clientShow);
		}

		if(ARTICLE_CLIENT_FROM){	//文章来源
			$clientFrom=I('get.clientFrom',0,'int');
			if($clientFrom>0){
				$where .=" and clientFrom={$clientFrom}";
			}
			$this->smarty->assign('clientFrom',C('CLIENT_FROM'));
			$this->smarty->assign('selectedSource',$clientFrom);
		}

		$auditStatus = ArticleModel::getAuditStatus();
		$this->smarty->assign('auditStatus',$auditStatus);

		if($audit>0){
			$where .=" and audit= '{$audit}' ";
		}

		$nickName=I('get.nickname',null);
		if($nickName){
			$where .=" and nickname like '{$nickName}' ";
		}


		$title=I('get.title',null);
		if($title){
			$where .=" and title like '%{$title}%'";
		}

		$articleM=M("article",null,DB_MAIN_CFG);


		$ofield=I('get.ofield');
		$otype=I('get.otype','');

		if(strcmp($otype,'')==0) {
			$field=null;
		}else{
			switch($ofield){
				case 1:
					$field ='praiseNum';
					break;
				case 2:
					$field ='viewNum';
					break;
				case 3:
					$field ='addTime';
					break;
				default:
					$field =null;
			}
		}


		if($field){
			$order="{$field} {$otype}";
		}else{
			$order=" addTime desc";
		}

		//主编标记
		if(checkPower('Article/ChiefEditor')==true){
		}else{
			$editorID = session(C('USER_AUTH_KEY'))+0;
			$where .=" and editor = {$editorID}";
		}


		$storeKv=array();
		if(IS_BROADCAST){
			$stores = UtilsModel::broadcast('get_fs_info',array('id'=>''),CURRENT_COMPANY);

			if($stores['status']==0){
				foreach($stores['data'] as $oneStore){
					$storeKv[$oneStore['id']]=$oneStore['name'];
				}
			}
		}


		if($export){
			ini_set('memory_limit', '512M');
			$list = $articleM
				->where($where)
				->field("title,contentType,nickname,commentNum,praiseNum,viewNum,addTime,audit,elite")
				->order($order)
				->select();
			$eliteStatus = ArticleModel::getEliteStatus();
			$type = getContentTypeKv();
			$data = array();


			foreach($list as $key => $val){
				$data[$key]=array();
				if(!$type[$val['contentType']]){
					$contentType = "未分类";
				} else{
					$contentType = $type[$val['contentType']];
				}
				$data[$key]['title'] = $val['title'];
				$data[$key]['type'] = $contentType;

				$data[$key]['nickname'] = $val['nickname'];
				$data[$key]['commentNum'] = $val['commentNum'];
				$data[$key]['praiseNum'] = $val['praiseNum'];
				$data[$key]['viewNum'] = $val['viewNum'];
				$data[$key]['addTime'] = date('Y-m-d H:i:s',$val['addTime']);
				$data[$key]['audit'] = $auditStatus[$val['audit']];
				$data[$key]['elite'] = $eliteStatus[$val['elite']];


			}

			exportExcel($data, array('标题','分类','作者','评论数','点赞数','阅读量','发布时间','审核状态','加精状态'),'文章列表_'.date('Ymd',time()));
			exit;
		} 
		else{
			$count = $articleM->where($where)->count();
			$this->smarty->assign('totalDataCount',$count);
			
			$limit = I('get.limit',10,'int');	//每页显示条数
			$Page = new Page($count,$limit);
			fetchPage($this->smarty,$Page);
			$list = $articleM->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();

			foreach($list as $key => $val){
				$list[$key]['nickname'] = $val['nickname'];
			}
			if(ARTICLE_PUSH){
				$this->smarty->assign('push',1);
			}else{
				$this->smarty->assign('push',0);
			}
			$this->smarty->assign('limit',$limit);
			$this->smarty->assign('ofield',$ofield);
			$this->smarty->assign('otype',$otype);

			$this->smarty->assign('contentType',getContentTypeKv());

			$this->smarty->assign('audit',$audit);
			$this->smarty->assign('nickname',$nickName);
			$this->smarty->assign('title',$title);

			$this->smarty->assign('list',$list);

			$this->smarty->assign('clientFromSwitch',ARTICLE_CLIENT_FROM);
			$this->smarty->assign('clientShowSwitch',ARTICLE_CLIENT_SHOW);
			$this->smarty->display('Article/index.html');
		}
	}


	//文章添加
	public function add(){
		$contentTypes = getContentTypeKv();
		$this->smarty->assign('contentType',$contentTypes);

		$channels=getChannelKv();
		$this->smarty->assign('channels',$channels);
		if(ARTICLE_SHOP) {
			//商家
			$shops = getShopKv();
			$this->smarty->assign('shops', $shops);
		}
		if(ARTICLE_CLIENT_SHOW){
			//展现渠道
			$clientShow=array_slice(C('CLIENT_SHOW'),1,null,true);
			$this->smarty->assign('clientShow',$clientShow);
		}

		$this->smarty->assign('picWidth',C("ARTICLE_LIST_PIC_WIDTH"));
		$this->smarty->assign('picHeight',C("ARTICLE_LIST_PIC_HEIGHT"));

		$uid = session('bind_uid');
		$nickName = session('bind_nickname');
		if($uid && !$nickName){
			$nickName = M('u_user_base',null,DB_GM_CFG)->where("uid={$uid}")->getField("nickname");
		}
		$this->smarty->assign('uid',$uid);
		$this->smarty->assign('nickname',$nickName);
		//商务经理
		if(ARTICLE_BUSINESS){
			$sysUser = getBusinessMangerList();
			$this->smarty->assign('sysUser',$sysUser);
		}

		$this->smarty->assign('clientShowSwitch',ARTICLE_CLIENT_SHOW);
		$this->smarty->assign('shopSwitch',ARTICLE_SHOP);
		$this->smarty->assign('relatedSwitch',ARTICLE_RELATED);
		$this->smarty->assign('authorSwitch',ARTICLE_AUTHOR);
		$this->smarty->assign('businessSwitch',ARTICLE_BUSINESS);

		$this->smarty->display('Article/edit.html');
	}

	//文章修改
	public function edit(){
		$id=I('get.id',0,'int');
		if($id<1) {
			$this->error("请指定文章");
		}

		$article=M('article',null,DB_MAIN_CFG)->where("id={$id}")->find();
		if(!$article){
			$this->error("指定文章不存在");
		}

		$this->smarty->assign('obj',$article);

		$contentTypes = getContentTypeKv();
		$this->smarty->assign('contentType',$contentTypes);

		$channels=getChannelKv();
		$this->smarty->assign('channels',$channels);

		$selectedChannel=explode(',',$article['channel']);
		$this->smarty->assign('selectedChannels',$selectedChannel);


		if(ARTICLE_CLIENT_SHOW) {
			//展现渠道

			$clientShow = array_slice(C('CLIENT_SHOW'), 1, null, true);
			$this->smarty->assign('clientShow', $clientShow);

			$selectedClient = explode(',', $article['clientShow']);
			$this->smarty->assign('selectedClients', $selectedClient);
		}

		$shops=getShopKv();
		$this->smarty->assign('shops',$shops);

		$related=$article['related'];
		$relateds=explode('|',$related);

		//商务经理
		if(ARTICLE_BUSINESS){
			$sysUser = getBusinessMangerList();
			$this->smarty->assign('sysUser',$sysUser);
			$this->smarty->assign('selectedSysUser',$article['businessManager']);
		}

		$uid = session('bind_uid');
		$nickName = session('bind_nickname');
		if($uid && !$nickName){
			$nickName = M('u_user_base',null,DB_GM_CFG)->where("uid={$uid}")->getField("nickname");
		}
		$this->smarty->assign('uid',$uid);
		$this->smarty->assign('nickname',$nickName);

		$fields=array();
		foreach($relateds as $v){
			$fields[]=explode(',',$v);
		}
		if(ARTICLE_SHOP) {
			//商户
			$shops = getShopKv();
			$this->smarty->assign('shops', $shops);
		}
		if(ARTICLE_RELATED){
			//关联
			$related=$article['related'];
			$relateds=explode('|',$related);

			$fields=array();
			foreach($relateds as $v){
				$fields[]=explode(',',$v);
			}
			$relatedNum=count($fields);
			$this->smarty->assign('relatedNum',$relatedNum);
			$this->smarty->assign('related',$fields);
		}

		$this->smarty->assign('picWidth',C("ARTICLE_LIST_PIC_WIDTH"));
		$this->smarty->assign('picHeight',C("ARTICLE_LIST_PIC_HEIGHT"));
		$this->smarty->assign('clientShowSwitch',ARTICLE_CLIENT_SHOW);
		$this->smarty->assign('shopSwitch',ARTICLE_SHOP);
		$this->smarty->assign('relatedSwitch',ARTICLE_RELATED);
		$this->smarty->assign('authorSwitch',ARTICLE_AUTHOR);
		$this->smarty->assign('businessSwitch',ARTICLE_BUSINESS);
		$this->smarty->display('Article/edit.html');
	}

	//审核
	public function audit(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定文章");
		}


		$articleM=M("article",null,DB_MAIN_CFG);

		$article=$articleM->where("id={$id}")->find();
		if(!$article){
			$this->error("指定的文章不存在");
		}

		//$newAudit=AUDIT_DEFAULT;
		switch($article['audit']+0){
			case AUDIT_DEFAULT:
				$newAudit=AUDIT_PASS;
				break;
			case AUDIT_PASS:
				$newAudit=AUDIT_UNPASS;
				break;
			case AUDIT_UNPASS:
				$newAudit=AUDIT_PASS;
				break;
			default:
				$newAudit=AUDIT_PASS;
				break;
		}

		$articleM->where("id={$id}")->setField('audit',$newAudit);
		$this->success("修改成功");




	}

	//加精
	public function elite(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定文章");
		}
		$articleM=M("article",null,DB_MAIN_CFG);
		$article=$articleM->where("id={$id}")->find();
		if(!$article){
			$this->error("指定的文章不存在");
		}
		switch($article['elite']+0){
			case 1:
				$newAudit=2;
				break;
			case 2:
				$newAudit=1;
				break;
			default:
				$newAudit=2;
				break;
		}

		$articleM->where("id={$id}")->setField('elite',$newAudit);
		$this->success("修改成功");
	}

	public function delete(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定文章");
		}
		$articleM=M("article",null,DB_MAIN_CFG);
		$articleInfo=$articleM->where("id={$id}")->find();
		if(!$articleInfo){
			$this->error("指定文章并不存在");
		};
		if($articleInfo['audit']==AUDIT_PASS){
			$this->error("已通过审核的文章不可删除");
		};
		$articleM->where("id={$id}")->delete();
		$this->success("删除成功");
	}






	//资讯添加或修改
	public function update(){
		$editorID = session(C('USER_AUTH_KEY'))+0;
		$id=I('post.id',0,'int');
		$title=I('post.title','');
		$titleLen=strlen($title);
		if($titleLen<C('TITLE_LENGTH_MIN')){
			$this->error('资讯标题长度不足'.C('TITLE_LENGTH_MIN'));
		}

		if($titleLen>C('TITLE_LENGTH_MAX')){
			$this->error('资讯标题长度过长'.C('TITLE_LENGTH_MAX'));
		}

		$contentType=I('post.contentType',0,'int');
		if($contentType<=CONTENT_TYPE_ALL || !array_key_exists($contentType,getContentTypeKv())){
			$this->error('文章内容类型指定错误');
		}
		$channel=I('post.channel',null);

		$needChannelNum = C('ARTICLE_CHANNEL_BELONG_NUM')+0;
		if(count($channel) < $needChannelNum){
			$this->error("至少从属{$needChannelNum}个栏目！");
		}

		$channel=implode(',',$channel);

		if(ARTICLE_CLIENT_SHOW){
			$clientShow=I('post.clientShow',null);
			if(count($clientShow)<=0){
				$this->error('文章必须指定至少一个展现渠道');
			}
			$clientShow=implode(',',$clientShow);

		} else{
			$clientShow=CLIENT_SHOW_WAP;	//
		}

		if(ARTICLE_AUTHOR){
			$uid = I('post.uid',0,'int');
		} else $uid = 0;



		$shopID			= I('post.shipID',0,'int');
		$listPic		= I('post.listPic');//列表图
		$content		= I('post.content');//内容
		$content		= htmlspecialchars_decode($content);
		$nativeRT		= UtilsModel::NativeThumb($content);
		$relativePhoto	= $nativeRT[0];
		$content		= $nativeRT[1];
		$nickName		= I('post.nickname');
		$recommend		= I('post.recommend',0,'int');//推荐指数
		if(ARTICLE_BUSINESS){
			$business 		= I('post.business',0,'intval');//商务经理
		} else $business = 0;


		if(ARTICLE_RELATED){
			$relatedType	= I('post.relatedType');
			$relatedID		= I('post.relatedID');
			$related		= array();
			foreach($relatedType as $k=>$v){
				if($v+0<1)continue;
				if($relatedID[$k]+0<1)continue;
				$related[]=$v.','.$relatedID[$k];
			}
			$related=implode('|',$related);
		} else{
			$related='';
		}
		$data=array(
			'editor'=>$editorID,
			'title'=>$title,
			'contentType'=>$contentType,
			'channel'=>$channel,
			'clientShow'=>$clientShow,
			'shopID'=>$shopID,
			'related'=>$related,
			'listPic'=>$listPic,
			'content'=>$content,
			'uid'=>$uid,
			'nickname'=>$nickName,
			'recommend'=>$recommend,
			'relativePhoto'=>implode(',',$relativePhoto),
			'businessManager'=>$business,
		);

		$articleM = M("article",null,DB_MAIN_CFG);
		if($business >0){
			$commerceM = M('commerce_evaluate',null,DB_MAIN_CFG);
			$editorName =  M("gm_sys_user",null,DB_GM_CFG)->where("id={$editorID}")->getField("username");
			$commerceName = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$business}")->getField("realName");
			$info['title'] = $title;
			$info['editorName'] = $editorName;
			$info['commerceID'] = $business;
			$info['commerceName'] = $commerceName;
			$info['status'] = EditorModel::COMMERCE_EVALUATE_OFF;
		}


		if($id==0){//新增
			$data['addTime']=time();
			$objID = $articleM->add($data);
			//商务信息保存
			if($business > 0){
				$info['objType'] = OBJ_TYPE_ARTICLE;
				$info['objID'] = $objID;
				$commerceM->add($info);
			}
			$this->success("添加成功");
		}else{//修改
			$articleM->where("id={$id}")->save($data);
			//商务信息修改
			if($business > 0){
				$commerceM->where("objType=".OBJ_TYPE_ARTICLE." and objID={$id}")->save($info);
			}
			$this->success("修改成功",u('index'));
		}
	}

	//每周热门活动
	public function everyHot(){
		$data=M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='EVERY_HOT_FOR_PC'")->find();
		if($data) {
			$data = unserialize($data['cfgValue']);
		}
		$leg = 10 - count($data);
		$objType=C('OBJ_TYPE');
		unset($objType[0]);
		$this->smarty->assign('objType',$objType);
		$this->smarty->assign('data',$data);
		$this->smarty->assign('leg',$leg);
		$this->smarty->display('Article/everyHot.html');
	}
	//保存
	public function everyHotSave(){
		$data = array();
		foreach($_POST['status'] as $ky=>$val){
			if($val && $_POST['order'][$ky]){
				$data[$_POST['order'][$ky]]['order'] = $_POST['order'][$ky];
				$data[$_POST['order'][$ky]]['type'] = $_POST['type'][$ky];
				$data[$_POST['order'][$ky]]['id'] = $_POST['status'][$ky];
			}
			asort($data);
		}
		if($data){
			$data = serialize($data);
			$res = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='EVERY_HOT_FOR_PC'")->save( array('cfgValue'=>$data ) );
			if($res) $this->ajaxReturn(array('status'=>0));
		}
		$this->ajaxReturn(array('status'=>1));
	}



	public function pushCenter(){
		$id=I('get.id',0,'int');
		if(!$id){
			$this->ajaxReturn(array('status'=>1,'msg'=>'指定文章不存在'));
		}
		$detail = ArticleModel::getArticleDetail($id);
		if($detail['pushCenter']==1){
			$this->ajaxReturn(array('status'=>1,'msg'=>'该文章已经推送过了'));
		}
		if($detail['status']!=0){
			$this->ajaxReturn($detail);
		}

		$detail['data']['sys']=CURRENT_COMPANY;
		$return = UtilsModel::broadcast('Article_push',$detail['data'],'starCenter');
		if($return['status']==0){
			ArticleModel::getInstance()->where('id='.$id)->setField('pushCenter',1);
		}
		$this->ajaxReturn($return);
	}

}
